'use client'; // 声明这是客户端组件，可使用React状态和浏览器API
import { useState, useEffect } from 'react'; // 导入React状态管理和副作用钩子
import Image from 'next/image'; // 导入Next.js的图片组件，优化图片加载
import Link from 'next/link'; // 导入Next.js的路由链接组件
import { useRouter, useSearchParams } from 'next/navigation'; // 导入Next.js的路由导航和查询参数钩子
import { toast } from 'react-toastify'; // 导入提示框组件
import styles from './personal.module.css'; // 导入CSS Modules样式文件
import { useAuth } from '@/hooks/contexts/AuthContext';
import Icon from "@/components/icon/Icon"
import type { IconPrefix, IconName } from '@fortawesome/fontawesome-svg-core';
import Favorite from "@/components/favorite/Favorite"


// 设置项类型定义
interface SettingItem {
    id: string; // 唯一标识
    icon: string; // 图标名称
    label: string; // 标题
    description: string; // 描述
    path: string; // 跳转路径
}

// 安全项目类型定义
interface SecurityItem {
    id: string; // 唯一标识
    icon: string; // 图标名称
    label: string; // 标题
    status: 'secure' | 'warning' | 'pending'; // 状态类型
    description: string; // 描述
    path: string; // 跳转路径
}

// 统计数据类型定义
interface StatData {
    id: string; // 唯一标识
    icon: string; // 图标名称
    label: string; // 标题
    value: string; // 数值
    trend: 'up' | 'down' | 'stable'; // 趋势类型
    trendValue: string; // 趋势数值
}

// 个人中心主组件
export default function ProfileCenter() {
    // 从URL查询参数获取默认标签页
    const searchParams = useSearchParams();
    const defaultTab = searchParams.get('tab') || 'profile';

    // 使用URL参数作为初始状态，确保是有效标签
    const [activeTab, setActiveTab] = useState(
        ['profile', 'settings', 'security', 'stats', 'favorites'].includes(defaultTab)
            ? defaultTab
            : 'profile'
    );

    const { user, logout, loading } = useAuth(); // 加载状态和用户信息
    const router = useRouter(); // 路由实例

    // 当activeTab变化时更新URL查询参数，保持状态同步
    useEffect(() => {
        const params = new URLSearchParams();
        if (activeTab !== 'profile') { // 只有非默认标签页才添加参数
            params.set('tab', activeTab);
        }
        router.push(`/profile?${params.toString()}`, { scroll: false });
    }, [activeTab, router]);

    // 加载用户数据的副作用
    useEffect(() => {
        const loadUserData = async () => {
            // 模拟API请求延迟
            await new Promise(resolve => setTimeout(resolve, 800));
        };
        loadUserData();
    }, []);

    // 处理退出登录
    const handleLogout = () => {
        logout();
        // 显示退出提示
        toast.info('已安全退出登录', {
            position: "top-center",
            autoClose: 1500,
            theme: 'colored',
        });
        // 延迟后跳转到首页
        setTimeout(() => router.push('/'), 1500);
    };

    // 设置项数据
    const settingItems: SettingItem[] = [
        {
            id: 'personal-info',
            icon: 'user',
            label: '个人信息',
            description: '修改您的姓名、头像和个人简介',
            path: '/profile/personal-info'
        },
        {
            id: 'account-settings',
            icon: 'cog',
            label: '账户设置',
            description: '管理您的登录账号和相关设置',
            path: '/profile/account-settings'
        },
        {
            id: 'notifications',
            icon: 'bell',
            label: '通知设置',
            description: '配置您接收通知的方式和内容',
            path: '/profile/notifications'
        },
        {
            id: 'privacy',
            icon: 'shield',
            label: '隐私设置',
            description: '管理您的个人数据和隐私权限',
            path: '/profile/privacy'
        }
    ];

    // 安全项目数据
    const securityItems: SecurityItem[] = [
        {
            id: 'password',
            icon: 'lock',
            label: '密码管理',
            status: 'secure',
            description: '上次更新于3个月前',
            path: '/profile/security/password'
        },
        {
            id: 'two-factor',
            icon: 'key',
            label: '双因素认证',
            status: 'warning',
            description: '未开启，开启后提高账户安全性',
            path: '/profile/security/two-factor'
        },
        {
            id: 'login-history',
            icon: 'history',
            label: '登录历史',
            status: 'secure',
            description: '最近登录正常，无异常记录',
            path: '/profile/security/login-history'
        },
        {
            id: 'linked-accounts',
            icon: 'link',
            label: '关联账户',
            status: 'pending',
            description: '1个关联账户，点击管理',
            path: '/profile/security/linked-accounts'
        }
    ];

    // 统计数据
    const statData: StatData[] = [
        {
            id: 'usage-time',
            icon: 'clock',
            label: '本月使用时长',
            value: '12.5小时',
            trend: 'up',
            trendValue: '+15%'
        },
        {
            id: 'favorites',
            icon: 'star',
            label: '收藏内容',
            value: '24条',
            trend: 'up',
            trendValue: '+3'
        },
        {
            id: 'contributions',
            icon: 'pen-to-square',
            label: '内容贡献',
            value: '8篇',
            trend: 'stable',
            trendValue: '0'
        },
        {
            id: 'shared-items',
            icon: 'share-from-square',
            label: '分享内容',
            value: '12次',
            trend: 'down',
            trendValue: '-2'
        }
    ];

    // 格式化日期为中文格式
    const formatDate = (dateString: string) => {
        const date = new Date(dateString);
        return new Intl.DateTimeFormat('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        }).format(date);
    };

    // 加载状态或用户数据未准备好时显示加载界面
    if (loading || !user) {
        return (
            <div className={styles['profile-loading']}>
                <div className={styles.container}>
                    <div className={styles['loading-spinner']}></div>
                    <p>正在加载您的个人信息...</p>
                </div>
            </div>
        );
    }

    // 主界面渲染
    return (
        <div className={styles['profile-page']}>
            {/* 页面头部 */}
            <header className={styles['profile-header']}>
                <div className={styles.container}>
                    <div className={styles['header-content']}>
                        <h1 className={styles['profile-title']}>个人中心</h1>
                        <div className={styles['header-actions']}>
                            {/* 通知按钮 */}
                            <button
                                className={styles['notification-btn']}
                                aria-label="通知"
                            >
                                <i className="fa fa-bell"></i>
                                {/* 通知数量徽章，有未读通知时显示 */}
                                {user.notificationCount > 0 && (
                                    <span className={styles['notification-badge']}>
                                        {user.notificationCount}
                                    </span>
                                )}
                            </button>
                            {/* 返回首页链接 */}
                            <Link href="/" className={styles['back-btn']}>
                                <i className="fa fa-arrow-left"></i>
                                <span>返回首页</span>
                            </Link>
                        </div>
                    </div>
                </div>
            </header>

            {/* 主内容区域 */}
            <main className={styles['profile-main']}>
                <div className={styles.container}>
                    <div className={styles['profile-grid']}>
                        {/* 侧边栏导航 */}
                        <aside className={styles['profile-sidebar']}>
                            <div className={styles['profile-card']}>
                                {/* 用户头像区域 */}
                                <div className={styles['profile-avatar-container']}>
                                    <div className={styles['avatar-wrapper']}>
                                        <Image
                                            src={user.avatar}
                                            alt={user.name}
                                            width={100}
                                            height={100}
                                            className={styles['profile-avatar']}
                                        />
                                        <button className={styles['edit-avatar-btn']}>
                                            <i className="fa fa-camera"></i>
                                        </button>
                                    </div>
                                    {/* 用户基本信息 */}
                                    <div className={styles['profile-info']}>
                                        <h2 className={styles['profile-name']}>{user.name}</h2>
                                        <p className={styles['profile-email']}>{user.email}</p>
                                        <div className={styles['member-badge']}>
                                            <span className={styles['badge-text']}>{user.memberLevel}</span>
                                        </div>
                                    </div>
                                </div>

                                {/* 导航菜单 */}
                                <nav className={styles['profile-nav']}>
                                    <ul>
                                        <li
                                            className={activeTab === 'profile' ? styles.active : ''}
                                            onClick={() => setActiveTab('profile')}
                                        >
                                            <i className="fa fa-user-circle"></i>
                                            <span>个人资料</span>
                                        </li>
                                        <li
                                            className={activeTab === 'settings' ? styles.active : ''}
                                            onClick={() => setActiveTab('settings')}
                                        >
                                            <i className="fa fa-cog"></i>
                                            <span>账户设置</span>
                                        </li>
                                        <li
                                            className={activeTab === 'security' ? styles.active : ''}
                                            onClick={() => setActiveTab('security')}
                                        >
                                            <Icon icon={['fas','shield-halved']} />
                                            <span>安全中心</span>
                                        </li>
                                        <li
                                            className={activeTab === 'stats' ? styles.active : ''}
                                            onClick={() => setActiveTab('stats')}
                                        >
                                            <Icon icon={['fas', 'chart-bar']} />
                                            <span>使用统计</span>
                                        </li>
                                        {/* 收藏夹按钮 */}
                                        <li
                                            className={activeTab === 'favorites' ? styles.active : ''}
                                            onClick={() => setActiveTab('favorites')}
                                        >
                                            <Icon icon={['fas', 'heart']} />
                                            <span>我的收藏</span>
                                        </li>
                                        {/* 退出登录按钮 */}
                                        <li className={styles['logout-item']} onClick={handleLogout}>
                                            <Icon icon={['fas', 'right-from-bracket']} />
                                            <span>退出登录</span>
                                        </li>
                                    </ul>
                                </nav>
                            </div>
                        </aside>

                        {/* 主内容区域 - 根据激活的标签页显示不同内容 */}
                        <div className={styles['profile-content']}>
                            {/* 个人资料标签页 */}
                            {activeTab === 'profile' && (
                                <div className={`${styles['profile-tab-content']} ${styles['animate-in']}`}>
                                    <div className={styles['section-header']}>
                                        <h2>个人资料</h2>
                                        <p>管理您的基本信息和个人偏好</p>
                                    </div>

                                    <div className={styles['profile-details']}>
                                        {/* 基本信息部分 */}
                                        <div className={styles['detail-section']}>
                                            <h3 className={styles['section-title']}>基本信息</h3>
                                            <div className={styles['info-grid']}>
                                                <div className={styles['info-item']}>
                                                    <label>姓名</label>
                                                    <span>{user.name}</span>
                                                </div>
                                                <div className={styles['info-item']}>
                                                    <label>电子邮箱</label>
                                                    <span>{user.email}</span>
                                                </div>
                                                <div className={styles['info-item']}>
                                                    <label>会员等级</label>
                                                    <span>{user.memberLevel}</span>
                                                </div>
                                                <div className={styles['info-item']}>
                                                    <label>注册日期</label>
                                                    <span>{formatDate(user.joinDate)}</span>
                                                </div>
                                                <div className={styles['info-item']}>
                                                    <label>上次登录</label>
                                                    <span>{user.lastLogin}</span>
                                                </div>
                                                <div className={styles['info-item']}>
                                                    <label>账户状态</label>
                                                    <span className={`${styles.status} ${styles.active}`}>正常</span>
                                                </div>
                                            </div>
                                            <button className={styles['edit-profile-btn']}>
                                                <i className="fa fa-edit"></i>
                                                <span>编辑基本信息</span>
                                            </button>
                                        </div>

                                        {/* 个人简介部分 */}
                                        <div className={styles['detail-section']}>
                                            <h3 className={styles['section-title']}>个人简介</h3>
                                            <div className={styles['bio-content']}>
                                                <p>热爱探索新知识，专注于人工智能与数据科学领域。希望通过这个平台连接更多志同道合的朋友，共同学习进步。</p>
                                            </div>
                                            <button className={styles['edit-bio-btn']}>
                                                <i className="fa fa-pencil"></i>
                                                <span>编辑个人简介</span>
                                            </button>
                                        </div>

                                    </div>
                                </div>
                            )}

                            {/* 账户设置标签页 */}
                            {activeTab === 'settings' && (
                                <div className={`${styles['settings-tab-content']} ${styles['animate-in']}`}>
                                    <div className={styles['section-header']}>
                                        <h2>账户设置</h2>
                                        <p>管理您的账户选项和偏好设置</p>
                                    </div>

                                    <div className={styles['settings-grid']}>
                                        {/* 渲染设置项列表 */}
                                        {settingItems.map((item) => (
                                            <Link
                                                key={item.id}
                                                href={item.path}
                                                className={styles['setting-card']}
                                            >
                                                <div className={styles['setting-icon']}>
                                                    <i className={`fa fa-${item.icon}`}></i>
                                                </div>
                                                <div className={styles['setting-info']}>
                                                    <h3 className={styles['setting-title']}>{item.label}</h3>
                                                    <p className={styles['setting-desc']}>{item.description}</p>
                                                </div>
                                                <div className={styles['setting-arrow']}>
                                                    <i className="fa fa-chevron-right"></i>
                                                </div>
                                            </Link>
                                        ))}
                                    </div>

                                    <div className={`${styles['section-header']} ${styles['mt-8']}`}>
                                        <h2>账户管理</h2>
                                        <p>管理您的账户生命周期选项</p>
                                    </div>

                                    <div className={styles['account-actions']}>
                                        {/* 暂时冻结账户 */}
                                        <div className={`${styles['action-card']} ${styles.warning}`}>
                                            <div className={styles['action-icon']}>
                                                <Icon icon={['fas','user-lock']}/>
                                            </div>
                                            <div className={styles['action-info']}>
                                                <h3 className={styles['action-title']}>暂时冻结账户</h3>
                                                <p className={styles['action-desc']}>冻结期间您将无法登录，所有数据将被保留</p>
                                            </div>
                                            <button className={styles['action-btn']}>
                                                <span>冻结账户</span>
                                            </button>
                                        </div>

                                        {/* 注销账户 */}
                                        <div className={`${styles['action-card']} ${styles.danger}`}>
                                            <div className={styles['action-icon']}>
                                                <i className="fa fa-user-times"></i>
                                            </div>
                                            <div className={styles['action-info']}>
                                                <h3 className={styles['action-title']}>注销账户</h3>
                                                <p className={styles['action-desc']}>注销后所有数据将被永久删除，无法恢复</p>
                                            </div>
                                            <button className={styles['action-btn']}>
                                                <span>注销账户</span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            )}

                            {/* 安全中心标签页 */}
                            {activeTab === 'security' && (
                                <div className={`${styles['security-tab-content']} ${styles['animate-in']}`}>
                                    <div className={styles['section-header']}>
                                        <h2>安全中心</h2>
                                        <p>保护您的账户安全和个人信息</p>
                                    </div>

                                    {/* 安全评分卡片 */}
                                    <div className={styles['security-score-card']}>
                                        <div className={styles['score-info']}>
                                            <h3>账户安全评分</h3>
                                            <div className={styles['score-value']}>75<span>分</span></div>
                                            <p className={styles['score-desc']}>良好，还可以进一步提高安全性</p>
                                        </div>
                                        <div className={styles['security-progress']}>
                                            <div className={styles['progress-bar']} style={{ width: '75%' }}></div>
                                        </div>
                                        <button className={styles['improve-security-btn']}>
                                            <i className="fa fa-shield"></i>
                                            <span>提升安全等级</span>
                                        </button>
                                    </div>

                                    {/* 安全项目列表 */}
                                    <div className={styles['security-grid']}>
                                        {securityItems.map((item) => (
                                            <Link
                                                key={item.id}
                                                href={item.path}
                                                className={styles['security-card']}
                                            >
                                                <div className={styles['security-icon']}>
                                                    <i className={`fa fa-${item.icon}`}></i>
                                                </div>
                                                <div className={styles['security-info']}>
                                                    <h3 className={styles['security-title']}>{item.label}</h3>
                                                    <p className={styles['security-desc']}>{item.description}</p>
                                                    <div className={`${styles['security-status']} ${styles[item.status]}`}>
                                                        {item.status === 'secure' && <span>安全</span>}
                                                        {item.status === 'warning' && <span>需注意</span>}
                                                        {item.status === 'pending' && <span>待处理</span>}
                                                    </div>
                                                </div>
                                                <div className={styles['security-arrow']}>
                                                    <i className="fa fa-chevron-right"></i>
                                                </div>
                                            </Link>
                                        ))}
                                    </div>
                                </div>
                            )}

                            {/* 使用统计标签页 */}
                            {activeTab === 'stats' && (
                                <div className={`${styles['stats-tab-content']} ${styles['animate-in']}`}>
                                    <div className={styles['section-header']}>
                                        <h2>使用统计</h2>
                                        <p>查看您的平台使用情况和数据统计</p>
                                    </div>

                                    {/* 统计数据卡片 */}
                                    <div className={styles['stats-grid']}>
                                        {statData.map((item) => (
                                            <div key={item.id} className={styles['stat-card']}>
                                                <div className={styles['stat-icon']}>
                                                    <Icon icon={['far',item.icon] as [IconPrefix,IconName]} />
                                                </div>
                                                <div className={styles['stat-info']}>
                                                    <h3 className={styles['stat-label']}>{item.label}</h3>
                                                    <div className={styles['stat-value-container']}>
                                                        <span className={styles['stat-value']}>{item.value}</span>
                                                        <span className={`${styles['stat-trend']} ${styles[item.trend]}`}>
                                                            {item.trend === 'up' && <i className="fa fa-arrow-up"></i>}
                                                            {item.trend === 'down' && <i className="fa fa-arrow-down"></i>}
                                                            {item.trend === 'stable' && <i className="fa fa-minus"></i>}
                                                            {item.trendValue}
                                                        </span>
                                                    </div>
                                                </div>
                                            </div>
                                        ))}
                                    </div>

                                    {/* 趋势图表区域 */}
                                    <div className={styles['chart-section']}>
                                        <h3 className={styles['section-title']}>使用趋势</h3>
                                        <div className={styles['chart-container']}>
                                            <div className={styles['chart-placeholder']}>
                                                <i className="fa fa-chart-line"></i>
                                                <p>使用趋势图表将在此显示</p>
                                            </div>
                                        </div>
                                        <div className={styles['chart-filters']}>
                                            <button className={`${styles['filter-btn']} ${styles.active}`}>周</button>
                                            <button className={styles['filter-btn']}>月</button>
                                            <button className={styles['filter-btn']}>季</button>
                                            <button className={styles['filter-btn']}>年</button>
                                        </div>
                                    </div>

                                    {/* 最近活动记录 */}
                                    <div className={styles['recent-activity']}>
                                        <h3 className={styles['section-title']}>最近活动</h3>
                                        <div className={styles['activity-list']}>
                                            <div className={styles['activity-item']}>
                                                <div className={styles['activity-icon']}>
                                                    <i className="fa fa-star"></i>
                                                </div>
                                                <div className={styles['activity-info']}>
                                                    <p className={styles['activity-text']}>收藏了文章《人工智能的未来发展趋势》</p>
                                                    <p className={styles['activity-time']}>今天 09:45</p>
                                                </div>
                                            </div>
                                            <div className={styles['activity-item']}>
                                                <div className={styles['activity-icon']}>
                                                    <i className="fa fa-download"></i>
                                                </div>
                                                <div className={styles['activity-info']}>
                                                    <p className={styles['activity-text']}>下载了资料《数据分析实战手册》</p>
                                                    <p className={styles['activity-time']}>昨天 16:20</p>
                                                </div>
                                            </div>
                                            <div className={styles['activity-item']}>
                                                <div className={styles['activity-icon']}>
                                                    <i className="fa fa-comment"></i>
                                                </div>
                                                <div className={styles['activity-info']}>
                                                    <p className={styles['activity-text']}>评论了讨论《机器学习在金融领域的应用》</p>
                                                    <p className={styles['activity-time']}>2023-06-08 10:15</p>
                                                </div>
                                            </div>
                                        </div>
                                        <button className={styles['view-all-activity']}>
                                            <span>查看全部活动</span>
                                            <i className="fa fa-chevron-down"></i>
                                        </button>
                                    </div>
                                </div>
                            )}
                            {/* 收藏内容标签页 */}
                            {activeTab === 'favorites' && (
                                <div className={`${styles['profile-tab-content']} ${styles['animate-in']}`}>
                                    <Favorite />
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </main>
        </div>
    );
}
